<script setup lang="ts">
import {reactive, onMounted, nextTick, ref,watch} from 'vue';
import {
  AccDeleteUserList,
  AccPostUserList,
  getUserList, postUser,
} from '/@/api/api'
import {Session} from '/@/utils/storage';
const getTOKEN = {Adminauthorization: Session.get('token')}
const upDataUrl = import.meta.env.VITE_API_URL + '/admin/user/importFromExcel';
import {ElMessage, ElMessageBox, UploadProps} from 'element-plus';
const importExcelRef = ref()
import {formatTime} from "/@/utils";
const avueFormRes = ref()
const avueCrudRef = ref()
const data = reactive({
  title:'Add',
  dialogShow: false,
  tabIndex: 0,
  dataList: [],
  show:false,
  page: {
    total: 10,
    currentPage: 1,
    pageSize: 10,
  },
  editState:0,
  option: {
    searchLabelWidth: 50,
    addBtn: false,
    printBtn: false,
    excelBtn: false,
    // searchSpan: 5,
    searchMenuSpan: 24,
    border: true,
    viewBtn: false,
    editBtn: false,
    delBtn: false,
    align: 'center',
    column: [
      {
        label: 'Start time',
        prop: 'createTime',
        minWidth: 150,
        search: true,
        searchType: 'daterange',
        searchSpan: 12,
        searchLabel: 'Time'
      },
      {
        label: 'Name',
        prop: 'firstName',
      },
      {
        label: 'surname',
        prop: 'lastName',
      },
      {
        label: 'User phone',
        prop: 'userPhone',
        search: true,
        searchLabelWidth:100,
      },
      {
        label: 'User code',
        prop: 'userCode',
        search: true,
        searchLabelWidth:100,
      },
      {
        label: 'Continent',
        prop: 'continent',
      },
      {
        label: 'UserCity',
        prop: 'userCity',
      },
      {
        label: 'UserApt',
        prop: 'userApt',
      },
      {
        label: 'User address',
        prop: 'userAddress',
      },
    ]
  },
  optionForm: {
    submitText:'Submit',
    emptyText	:'Empty',
    column: [
      {
        label: 'Phone',
        span: 24,
        prop: 'userPhone',
        type: 'input',
        rules: [
          {
            required: true,
            message: "Please enter your mobile phone number",
            trigger: "blur"
          }
        ]
      },
      {
        label: 'Last Name',
        span: 24,
        prop: 'lastName',
        type: 'input',
        labelWidth:120,
        rules: [
          {
            required: true,
            message: "Please enter a name for the label",
            trigger: "blur"
          }
        ]
      },
      {
        label: 'First Name',
        span: 24,
        prop: 'firstName',
        type: 'input',
        labelWidth:120,
        rules: [
          {
            required: true,
            message: "Please enter a name for the label",
            trigger: "blur"
          }
        ]
      },
      {
        label: 'Address',
        span: 24,
        prop: 'userAddress',
        type: 'input',
        labelWidth:120,
        rules: [
          {
            required: true,
            message: "Please enter an address",
            trigger: "blur"
          }
        ]
      },
      {
        label: 'State',
        span: 24,
        prop: 'continent',
        type: 'input',
        labelWidth:120,
        rules: [
          {
            required: true,
            message: "Please enter an continent",
            trigger: "blur"
          }
        ]
      },
      {
        label: 'City',
        span: 24,
        prop: 'userCity',
        type: 'input',
        labelWidth:120,
        rules: [
          {
            required: true,
            message: "Please enter an userCity",
            trigger: "blur"
          }
        ]
      },
      {
        label: 'Apartment',
        span: 24,
        prop: 'userApt',
        type: 'input',
        labelWidth:120,
        rules: [
          {
            required: true,
            message: "Please enter an User apt",
            trigger: "blur"
          }
        ]
      },
      {
        label: 'Zip code',
        span: 24,
        prop: 'zipCode',
        type: 'input',
        labelWidth:120,
        rules: [
          {
            required: true,
            message: "Please enter an zipCode",
            trigger: "blur"
          }
        ]
      },
      {
        label: 'Password',
        span: 24,
        prop: 'userPaw',
        type: 'password',
        labelWidth:120
      },
    ]
  },
  form: {
    userPhone: ''
  },
  formSearch:{
    userPhone: '',
  },
  curriculumForm:{},
  fileList:[],
  id:''
})

onMounted(() => {

})
const bannerList = (row:object = {}) => {
  let page = {
    pageIndex: data.page.currentPage,
    pageSize: data.page.pageSize
  }
  getUserList({...page,...row}).then((res: any) => {
    console.log(res)
    if (res.code === 200) {
      data.dataList = res.data.list
      data.page.total = res.data.total
    }

  })
}
const onLoad = (e:any) => {
  console.log(e)
  data.page.currentPage = e.currentPage
  data.page.pageSize = e.pageSize
  bannerList()
}
const refreshChange = () => {

  bannerList()
}
const Edit = (row:any) => {
  data.curriculumForm = row
  data.form = row
  data.editState = 1
  data.dialogShow = true
}
const forbiddenFun = () => {
  AccDeleteUserList({ids:data.id}).then((res: any) => {
    bannerList()
    if (res.code === 200) {
      ElMessage({
        showClose: true,
        message: 'The deletion is successful',
        type: 'success',
      })
      data.show = false
    }
  })
}
const Delete = (row:any) => {
  data.show = true
  data.id = row.userId
}
const handleSubmit = (form: object, done: any) => {
  if(data.editState === 1){
    AccPostUserList(data.form.userId ? data.form : [data.form]).then((res: any) => {
      if (res.code === 200) {
        ElMessage({
          showClose: true,
          message: 'The addition was successful',
          type: 'success',
        })
      }
      data.dialogShow = false
      bannerList()
      done()
    })
  }
  if(data.editState === 0){
    postUser([data.form]).then((res: any) => {
      if (res.code === 200) {
        ElMessage({
          showClose: true,
          message: 'The new is successful',
          type: 'success',
        })
      }
      data.dialogShow = false
      bannerList()
      done()
    })
  }
}
const handleReset = () => {
  bannerList()
}
const resetChange = (item: any) => {
  data.formSearch.userPhone = ''
  bannerList()
}
const searchChange = (params: any, done: any) => {
  console.log(params)
  delete params.userPaw
  delete params.userPhone
  done()
  bannerList({
    startTime: params.createTime ? formatTime(params.createTime[0], 'YYYY-MM-DD') : '',
    endTime: params.createTime ? formatTime(params.createTime[1], 'YYYY-MM-DD') : '',
    userPhone: data.formSearch.userPhone,
    ...params
  })
}
const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
  console.log(uploadFile)
}
const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  console.log(file, uploadFiles)
}
const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
      `Cancel the transfer of ${uploadFile.name} ?`
  ).then(
      () => true,
      () => false
  )
}
const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning(
      `The limit is 1, you selected ${files.length} files this time, add up to ${
          files.length + uploadFiles.length
      } totally`
  )
}
const beforeSuccess = () => {
  importExcelRef.value.clearFiles();
  bannerList()
}
const NewFun = () => {
  data.form = {}
  data.editState = 0
  data.dialogShow = true
  nextTick(()=>{
    avueFormRes.value.resetForm()
  })
}
const formatPhoneNumber = (phoneNumber:any) => {
  const cleanedInput = phoneNumber.replace(/[^0-9]/g, '');
  if (cleanedInput.length !== 10) {
    return phoneNumber;
  }
  const formattedNumber = `${cleanedInput.slice(0, 3)}-${cleanedInput.slice(3, 6)}-${cleanedInput.slice(6)}`;
  return formattedNumber;
}
</script>
<template>
  <div class="layout-pd">
    <div class="carousel-box">
      <avue-crud ref="avueCrudRef" v-model:page="data.page" :data="data.dataList" :option="data.option"
                 @on-load="onLoad"
                 @search-reset="resetChange" @refresh-change="refreshChange" @search-change="searchChange">
        <template #menu-left="{}">
          <div style="display: flex;margin-bottom: 10px">
            <div style="margin-right: 20px">
              <el-upload
                  ref="importExcelRef"
                  v-model:file-list="data.fileList"
                  class="upload-demo"
                  :action="upDataUrl"
                  multiple
                  :headers="getTOKEN"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :before-remove="beforeRemove"
                  :on-success="beforeSuccess"
                  :limit="1"
                  :on-exceed="handleExceed"
              >
                <el-button type="primary">Click to upload</el-button>
              </el-upload>
            </div>
            <el-button type="primary" @click="NewFun">New</el-button>
          </div>
        </template>
        <template #userPhone-search="{disabled,size}">
          <el-input
              v-model="data.formSearch.userPhone"
              placeholder="Please enter a phone number"
              :maxlength="12"
              :formatter="(value) => (value ? formatPhoneNumber(value) : '')"
          />
        </template>
        <template #menu="{row}">
          <el-button text type="primary" @click="Edit(row)">Edit</el-button>
          <el-button text type="primary" @click="Delete(row)">Delete</el-button>
        </template>
      </avue-crud>
    </div>
    <el-dialog v-if="data.dialogShow" v-model="data.dialogShow" :title="data.title" width="50%">
      <avue-form ref="avueFormRes" :option="data.optionForm" v-model="data.form" @submit="handleSubmit"  @reset-change="handleReset">
        <template #userPhone="{row}">
          <el-input
              v-model="data.form.userPhone"
              placeholder="Please enter a phone number"
              :maxlength="12"
              :formatter="(value) => (value ? formatPhoneNumber(value) : '')"
          />
        </template>
      </avue-form>
    </el-dialog>
    <el-dialog v-model="data.show" title="Warning" width="30%">
      <span>Are you sure you want to delete the data?</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.show = false">Cancel</el-button>
          <el-button type="primary" @click="forbiddenFun()">OK</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.carousel-box {
  width: 100%;
  box-sizing: border-box;
  background: var(--el-color-white);
  padding: 20px;
}

.item-img {
  width: 100%;

  img {
    width: 50%;
  }
}

::v-deep .avue-form__row {
  margin-bottom: 20px;
}
::v-deep .el-select {
  width: 100% !important;
}
</style>